package com.lightheart.sphr.xiaobinggan.design

import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ViewTreeObserver
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import com.lightheart.sphr.xiaobinggan.R
import com.lightheart.sphr.xiaobinggan.design.utils.ObservableScrollView
import com.lightheart.sphr.xiaobinggan.utils.StatusbarUtils
import kotlinx.android.synthetic.main.activity_design.*
import kotlinx.android.synthetic.main.include_header_itl.*

/****
 *https://www.jianshu.com/p/ec0d4a73c970
 * https://www.jianshu.com/p/36e974cb3af5
 */

class DesignActivity : AppCompatActivity(), ObservableScrollView.OnObservableScrollViewListener {


    private var mHeight = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_design)
        //设置透明状态栏
        StatusbarUtils.enableTranslucentStatusbar(this)

        //获取标题栏高度
        val viewTreeObserver: ViewTreeObserver = tv_main_topContent.viewTreeObserver
        viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                tv_main_topContent.viewTreeObserver.removeOnGlobalLayoutListener(this)
                mHeight = tv_main_topContent.height - ll_header_content.height //这里取的高度应该为图片的高度-标题栏
                //注册滑动监听
                sv_main_content.setOnObservableScrollViewListener(this@DesignActivity)
            }
        })
    }

    override fun onObservableScrollViewListener(l: Int, t: Int, oldl: Int, oldt: Int) {
        if (t <= 0) {
            //顶部图处于最顶部，标题栏透明
            sv_main_content.setBackgroundColor(Color.argb(0, 48, 63, 159))
        } else if (t > 0 && t < mHeight) {
            //滑动过程中，渐变
            val scale = t.toFloat() / mHeight //算出滑动距离比例
            val alpha = 255 * scale //得到透明度
            sv_main_content.setBackgroundColor(Color.argb(alpha.toInt(), 48, 63, 159))
        } else {
            //过顶部图区域，标题栏定色
            sv_main_content.setBackgroundColor(Color.argb(255, 48, 63, 159))
        }
    }
}